package com.jason.quectel0805.activities;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jason.quectel0805.R;
import com.jason.quectel0805.receivers.MyBroadcastReceiver;
import com.jason.quectel0805.services.MyService;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "jasonwan";
    MyBroadcastReceiver myBroadcastReceiver;
    private TextView tvShow;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Log.d(TAG, "handleMessage: " + msg.obj);
                    Log.d(TAG, "handleMessage: 当前线程：" + Thread.currentThread().getName());
                    tvShow.setText((CharSequence) msg.obj);
                    break;
                case 2:
                    Log.d(TAG, "handleMessage: " + msg.obj);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: " + Thread.currentThread().getName());
        setContentView(R.layout.activity_main);

        //    Linearlayout：线性布局，两个方向：水平和垂直
        tvShow = findViewById(R.id.tv_show);
        //单击监听
        Button btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "跳转成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.setClass(MainActivity.this, SecondActivity.class);
                //intent.putExtra("name", "jason");
                //intent.putExtra("age", "19");
                Person jason = new Person("Jason", "19");
                intent.putExtra("person", jason);
                //临时以SingleInstance的启动模式启动这个Activity
                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                //Intent intent = new Intent();
                //intent.setAction(Intent.ACTION_VIEW);
                //intent.setData(Uri.parse("http://www.quectel.com"));
                //intent.setType("text/html");
                //
                //intent.setAction(Intent.ACTION_DIAL);
                //intent.setData(Uri.parse("tel://18272164317"));
                ////intent.setType("text/html");
                //startActivity(intent);
            }
        });
        //长按监听
        btnLogin.setOnLongClickListener(new View.OnLongClickListener() {
            /**
             *
             * @param view
             * @return 代表当前长按操作是否拦截当前的的整个事件
             */
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(MainActivity.this, "我被长按点击了", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        //文本框输入监听
        EditText etInput = findViewById(R.id.et_input);
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.d(TAG, "beforeTextChanged: " + charSequence);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.d(TAG, "onTextChanged: " + charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                Log.d(TAG, "afterTextChanged: " + editable.toString());
            }
        });

        //    单选框选择监听
        RadioGroup rgSex = findViewById(R.id.rg_sex);
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_man) {
                    Toast.makeText(MainActivity.this, "你选择了男", Toast.LENGTH_SHORT).show();
                } else if (i == R.id.rb_woman) {
                    Toast.makeText(MainActivity.this, "你选择了女", Toast.LENGTH_SHORT).show();
                } else if (i == R.id.rb_unknown) {
                    Toast.makeText(MainActivity.this, "你选择了未知", Toast.LENGTH_SHORT).show();
                } else {

                }
            }
        });

        //复选框选择监听
        CheckBox cbSwimming = findViewById(R.id.cb_swimming);
        CheckBox cdPlayFootbal = findViewById(R.id.cb_playFootball);
        CheckBox cbStudy = findViewById(R.id.cb_study);
        cbSwimming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "你选中了游泳选项", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "你取消了游泳选项", Toast.LENGTH_SHORT).show();
                }
            }
        });
        cdPlayFootbal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "你选中了打球选项", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "你取消了打球选项", Toast.LENGTH_SHORT).show();
                }
            }
        });
        cbStudy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "你选中了学习选项", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "你取消了学习选项", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //    滑动监听
        NestedScrollView nsvRoot = findViewById(R.id.nsv_root);
        nsvRoot.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Log.d(TAG, "onScrollChange: scrollX=" + scrollX + ",scrollY=" + scrollY);
            }
        });

        //Intent intent = new Intent();
        //intent.setAction(Intent.ACTION_VIEW);
        //intent.setData(Uri.parse("http://www.quectel.com"));
        //intent.setAction(Intent.ACTION_DIAL);
        //intent.setData(Uri.parse("tel://18272164317"));
        //intent.setType("text/html");
        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.putExtra("key", "value");
        //startActivity(intent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    public void sendMyBroadcast(View view) {
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter("com.jason.quectel");
        registerReceiver(myBroadcastReceiver, intentFilter);

        Log.d(TAG, "sendBroadcast: 点击了发送广播按钮");
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        intent.setAction("com.jason.quectel");
        intent.putExtra("battery", "10%");
        sendBroadcast(intent);

        //Intent intent = new Intent(this, MyReceiver.class);
        //intent.setAction("com.jason.quectel");
        //sendBroadcast(intent);


    }

    public void modifyUIInWorkThread(View view) {
        //String fileContent = "我是大文件";
        //Log.d(TAG, "run: 读取了一个大文件，文件内容：" + fileContent);
        //如果文件比较小（几KB），OK，没什么影响，但如果文件比较大（500MB，>1GB），那么界面在明显的卡顿
        new Thread(new Runnable() {
            @Override
            public void run() {
                String fileContent = "我是大文件";
                Log.d(TAG, "run: 读取了一个大文件，文件内容：" + fileContent);
                //android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                //Android系统规定，只能在主线程创建和更新UI，不能在子线程（工作线程）操作UI,而且也规定了
                //在主线程当中也不能执行耗时操作，例如：读取大文件，网络通信，操作本地数据库
                //tvShow.setText(fileContent);
                //TextView textView = new TextView(MainActivity.this);

                //    通过Handler将线程切换到主线程上，然后进行UI操作
                Message message = Message.obtain();
                message.what = 1;
                message.obj = fileContent;
                //message.setTarget();
                mHandler.sendMessage(message);

                //Message message2 = Message.obtain();
                //message2.what = 2;
                //message2.obj = "我是message2";
                ////message.setTarget();
                //mHandler.sendMessage(message2);

            }
        }).start();
    }

    /**
     * 启动Service
     *
     * @param view
     */
    public void startMyService(View view) {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        intent.putExtra("download_url", "https://www.baidu.com/jfdskldjfla.txt");
        startService(intent);
        //bindService(intent, new MyServiceConnection(), Context.BIND_AUTO_CREATE);
    }

    class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onBindingDied(ComponentName name) {
            ServiceConnection.super.onBindingDied(name);
        }

        @Override
        public void onNullBinding(ComponentName name) {
            ServiceConnection.super.onNullBinding(name);
        }
    }
}